<template>
  <div class="page wrap">
    <van-swipe
      class="fit-height"
      ref="swiper"
      :initial-swipe="active"
      :loop="false"
      :show-indicators="false"
      :stop-propagation="false"
      @change="onChange"
    >
      <van-swipe-item v-for="(page, index) in pages" :key="index">
          <Suspense> 
            <template #default> 
              <component :ref="`page${index}`" :is="page" :value="index"></component>
            </template>
            <template #fallback> 
              <div class="loading flex flex-items-center">
                <img src="../assets/img/loading.gif"><span>正在加载...</span>
              </div>
            </template>
          </Suspense>
      </van-swipe-item>
    </van-swipe>
  </div>
</template>

<script>
import Config from "@/api/config";
import { setStatusBar } from "@/utils";
import { defineAsyncComponent, getCurrentInstance, nextTick, onMounted, provide, reactive, ref, toRaw } from "vue";
import { useRoute, useRouter } from "vue-router";

const Home = defineAsyncComponent(() =>  import('@/views/home'))
const Exchange = defineAsyncComponent(() =>  import('@/views/exchange'))
const Wallet = defineAsyncComponent(() =>  import('@/views/wallet'))
const Ucenter = defineAsyncComponent(() =>  import('@/views/ucenter'))

export default {
  setup(params, ctx) {
    const pages = [Home, Exchange, Wallet, Ucenter];
    const swiper = ref(null);
    const self = getCurrentInstance();
    const route = useRoute();
    const router = useRouter();
    const active = ref((()=>{
      const _active = route.params.active << 0
      return _active < pages.length && _active || 0
    })());
    const pagesResolve = reactive({})
    provide('pagesResolve', pagesResolve)
    provide('pageActive', active)

    function onChange(index) {
      nextTick(() => {
        active.value = index;
        router.replace({ params: { active: index } });
        self.root.refs.nav.active = index;
        if(pagesResolve[index]){
          setTimeout(()=>{
            pagesResolve[index]()
            delete pagesResolve[index]
          },500)
        }
      });
    }

    onMounted(() => {
      self.root.refs.nav.swiper = swiper.value;
      setStatusBar();
    });

    return {
      pages,
      active,
      swiper,
      onChange,
    };
  },
};
</script>

<style lang="less" scoped>
.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  img {
    width: 18px;
    height: 18px;
    margin-right: 5px;
  }
  span {
    display: inline-block;
    margin-top: 2px;
  }
}
</style>
